/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.PurchaseData;
import me.zhengjie.modules.system.domain.SalePoorProduct;
import me.zhengjie.modules.system.domain.SaleWellProduct;
import me.zhengjie.modules.system.repository.SalePoorProductRepository;
import me.zhengjie.modules.system.repository.SaleWellProductRepository;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.SalePoorProductMapper;
import me.zhengjie.modules.system.service.mapstruct.SaleWellProductMapper;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.PurchaseDataRepository;
import me.zhengjie.modules.system.service.PurchaseDataService;
import me.zhengjie.modules.system.service.mapstruct.PurchaseDataMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

import me.zhengjie.utils.PageResult;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 李忠臻
* @date 2024-02-20
**/
@Service
@RequiredArgsConstructor
public class PurchaseDataServiceImpl implements PurchaseDataService {

    private final PurchaseDataRepository purchaseDataRepository;
    private final PurchaseDataMapper purchaseDataMapper;

    private final SaleWellProductMapper saleWellProductMapper;
    private final SalePoorProductMapper salePoorProductMapper;

    private final SaleWellProductRepository saleWellProductRepository;
    private final SalePoorProductRepository salePoorProductRepository;
    @Override
    public PageResult<PurchaseDataDto> queryAll(PurchaseDataQueryCriteria criteria, Pageable pageable){
        Page<PurchaseData> page = purchaseDataRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(purchaseDataMapper::toDto));
    }

    @Override
    public List<PurchaseDataDto> query(PurchaseDataQueryCriteria criteria) {
        return purchaseDataMapper.toDto(purchaseDataRepository.findLastDataByModel(criteria.getModel(),
                criteria.getFromNowDay(), criteria.getGreaterFromNowDay(), criteria.getCustomer()));
    }

    @Override
    public PageResult<SaleWellProductDto> querySaleWellProduct(SaleWellProductQueryCriteria criteria, Pageable pageable) {
        Page<SaleWellProduct> page = saleWellProductRepository.querySaleWellProduct(criteria.getFromNowDay(), criteria.getPurchaseTime(), pageable);
        return PageUtil.toPage(page.map(saleWellProductMapper::toDto));
    }

    @Override
    public PageResult<SalePoorProductDto> querySalePoorProduct(SalePoorProductQueryCriteria criteria, Pageable pageable) {
        Page<SalePoorProduct> page = salePoorProductRepository.querySalePoorProduct(criteria.getFromNowDay(), criteria.getGreaterFromNowDay(), criteria.getPurchaseTime(), pageable);
        return PageUtil.toPage(page.map(salePoorProductMapper::toDto));
    }

    @Override
    public List<PurchaseDataDto> queryAll(PurchaseDataQueryCriteria criteria){
        return purchaseDataMapper.toDto(purchaseDataRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<SaleWellProductDto> querySaleWellProduct(SaleWellProductQueryCriteria criteria) {
        return saleWellProductMapper.toDto(saleWellProductRepository.querySaleWellProduct(criteria.getFromNowDay(), criteria.getPurchaseTime()));
    }

    @Override
    public List<SalePoorProductDto> querySalePoorProduct(SalePoorProductQueryCriteria criteria) {
        return salePoorProductMapper.toDto(salePoorProductRepository.querySalePoorProduct(criteria.getFromNowDay(), criteria.getGreaterFromNowDay(), criteria.getPurchaseTime()));
    }

    @Override
    @Transactional
    public PurchaseDataDto findById(Long id) {
        PurchaseData purchaseData = purchaseDataRepository.findById(id).orElseGet(PurchaseData::new);
        ValidationUtil.isNull(purchaseData.getId(),"PurchaseData","id",id);
        return purchaseDataMapper.toDto(purchaseData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PurchaseData resources) {
//        if(purchaseDataRepository.findById(resources.getId()) != null){
//            throw new EntityExistException(PurchaseData.class,"id",resources.getId().toString());
//        }
        purchaseDataRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PurchaseData resources) {
        PurchaseData purchaseData = purchaseDataRepository.findById(resources.getId()).orElseGet(PurchaseData::new);
        int originalQuantity = purchaseData.getOriginalQuantity() == null ? purchaseData.getQuantity() : purchaseData.getOriginalQuantity();
        if (resources.getQuantity() > originalQuantity) {
            throw new BadRequestException("采购单中的采购数不能超过原采购数，请修改后重新提交!");
        }

        int o = purchaseData.getQuantity();
        ValidationUtil.isNull( purchaseData.getId(),"PurchaseData","id",resources.getId());
        purchaseData.copy(resources);
        purchaseData.setOriginalQuantity(purchaseData.getOriginalQuantity() == null ? o : purchaseData.getOriginalQuantity());
        purchaseData.setOnPassageQuantity(new BigDecimal(purchaseData.getQuantity()).subtract(new BigDecimal(purchaseData.getGodownQuantity())).intValue());
        purchaseDataRepository.save(purchaseData);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            purchaseDataRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<PurchaseDataDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PurchaseDataDto purchaseData : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("B2B号", purchaseData.getB2b());
            map.put("序号", purchaseData.getIndex());
            map.put("料号；型号", purchaseData.getModel());
            map.put("原采购数量", purchaseData.getOriginalQuantity());
            map.put("采购数量", purchaseData.getQuantity());
            map.put("入库数量", purchaseData.getGodownQuantity());
            map.put("在途数量", purchaseData.getOnPassageQuantity());
            map.put("期望交付日", purchaseData.getExpectedDeliveryDate());
//            map.put("备注", purchaseData.getRemark());
            map.put("客户", purchaseData.getCustomer());
//            map.put("创建者", purchaseData.getCreateBy());
//            map.put("更新者", purchaseData.getUpdateBy());
            map.put("创建日期", purchaseData.getCreateTime());
//            map.put("更新时间", purchaseData.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}